const md5 = require('md5');
const Admin = require('../models/Admin');
const validate = require('validate.js');
exports.addAdmin = async function (adminObj) {
  const rule = {
    loginPwd: {
      presence: {
        allowEmpty: false,
      },
      length: {
        minimum: 2,
        maximum: 8,
      },
    },
    loginId: {
      presence: {
        allowEmpty: false,
      },
      length: {
        minimum: 2,
        maximum: 8,
      },
    },
  };
  // const result = validate.validate(adminObj, rule); // 同步验证;
  // await validate.async(adminObj, rule); // 异步验证 会直接 任何一个 reject的 Promise
  // adminObj.loginPwd = md5(adminObj.loginPwd);
  // const ins = await Admin.create(adminObj);
  // return ins.JSON();
  let ins;

  if (!result) {
    // result 什么都没有 代表 验证通过
    adminObj.loginPwd = md5(adminObj.loginPwd);
    ins = await Admin.create(adminObj).toJSON();
    ins = ins.toJSON();
  } else {
    // 这里抛出一个错误  外层可以捕获到
    throw new Error('账号密码格式错误！');
  }

  return ins;
};

exports.deleteAdmin = async function (adminId) {
  const result = await Admin.destroy({
    where: {
      id: adminId,
    },
  });
  return result;
};

exports.updateAdmin = async function (id, adminObj) {
  if (adminObj.loginPwd) {
    adminObj.loginPwd = md5(adminObj.loginPwd);
  }
  const result = await Admin.update(adminObj, {
    where: {
      id,
    },
  });
  return result;
};

exports.login = async function (loginId, loginPwd) {
  loginPwd = md5(loginPwd);
  const result = await Admin.findOne({
    where: {
      loginId,
      loginPwd,
    },
  });
  if (result && result.loginId === loginId) {
    return result.toJSON();
  }
  return null;
};

exports.getAdminById = async function (id) {
  const result = await Admin.findByPk(id);
  if (result) {
    return result.toJSON();
  }
  return null;
};

exports.getAdmins = async function () {
  const result = await Admin.findAll();
  return JSON.parse(JSON.stringify(result));
};
